package cn.lingyangwl.agile.plugin.file.preview.service.impl;

import cn.lingyangwl.framework.core.response.Resp;
import cn.lingyangwl.framework.core.response.RetOps;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.agile.plugin.file.preview.config.ConfigConstants;
import cn.lingyangwl.agile.plugin.file.preview.filter.BaseUrlFilter;
import cn.lingyangwl.agile.plugin.file.preview.model.FileAttribute;
import cn.lingyangwl.agile.plugin.file.preview.model.FilePreviewRS;
import cn.lingyangwl.agile.plugin.file.preview.service.FileHandlerService;
import cn.lingyangwl.agile.plugin.file.preview.service.FilePreview;
import cn.lingyangwl.agile.plugin.file.preview.utils.DownloadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.net.URLEncoder;
import java.util.List;

/**
 * 处理pdf文件
 *
 * @author shenguangyang
 * @since 1.0.0
 */
@Slf4j
@Service
public class PdfFilePreviewImpl implements FilePreview {

    private final FileHandlerService fileHandlerService;
    private final OtherFilePreviewImpl otherFilePreview;
    private static final String FILE_DIR = ConfigConstants.getFileDir();

    public PdfFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) {
        this.fileHandlerService = fileHandlerService;
        this.otherFilePreview = otherFilePreview;
    }

    @Override
    public FilePreviewRS filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
        try {
            String fileName = fileAttribute.getName();
            String officePreviewType = fileAttribute.getOfficePreviewType();
            String baseUrl = BaseUrlFilter.getBaseUrl();
            String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
            String outFilePath = FILE_DIR + pdfName;
            if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) {
                //当文件不存在时，就去下载
                if (!fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
                    Resp<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
                    if (!RetOps.of(response).isSuccess()) {
                        throw new BizException(response.getMsg());
                    }
                    outFilePath = response.getData();
                    if (ConfigConstants.isCacheEnabled()) {
                        // 加入缓存
                        fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath));
                    }
                }
                List<String> imageUrls = fileHandlerService.pdf2jpg(outFilePath, pdfName, baseUrl);
                if (imageUrls == null || imageUrls.size() < 1) {
                    throw new BizException("pdf转图片异常，请联系管理员");
                }
                model.addAttribute("imgurls", imageUrls);
                model.addAttribute("currentUrl", imageUrls.get(0));
                if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)) {
                    return FilePreviewRS.builder().type(OFFICE_PICTURE_FILE_PREVIEW_PAGE).build();
                } else {
                    return FilePreviewRS.builder().type(PICTURE_FILE_PREVIEW_PAGE).build();
                }
            } else {
                // 不是http开头，浏览器不能直接访问，需下载到本地
                if (url != null && !url.toLowerCase().startsWith("http")) {
                    if (!fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
                        Resp<String> response = DownloadUtils.downLoad(fileAttribute, pdfName);
                        if (!RetOps.of(response).isSuccess()) {
                            throw new BizException(response.getMsg());
                        }
                        model.addAttribute("pdfUrl", fileHandlerService.getRelativePath(response.getData()));
                        if (ConfigConstants.isCacheEnabled()) {
                            // 加入缓存
                            fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath));
                        }
                    } else {
                        pdfName =   URLEncoder.encode(pdfName, "utf-8").replaceAll("\\+", "%20");
                        model.addAttribute("pdfUrl", pdfName);
                    }
                } else {
                    model.addAttribute("pdfUrl", url);
                }
            }
            return FilePreviewRS.builder().type(PDF_FILE_PREVIEW_PAGE).build();
        } catch (Exception e) {
            log.error("error: ", e);
            throw new BizException("预览失败");
        }
    }
}
